package com.liuhong.shoping.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuhong.shoping.dao.ProductMapper;
import com.liuhong.shoping.entity.Product;
import com.liuhong.shoping.vo.in.GetDataPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuhong
 * @since 2020-12-05
 */
@RestController
public class ProductController {
    @Autowired
    ProductMapper productMapper;

    @Value("${resources.path.image}")
    String imagePath;

    @PostMapping("/product/getProduct")
    public List<Product> getProduct(@RequestBody GetDataPage dataPage)
    {
        QueryWrapper<Product> queryWrapperProduct = new QueryWrapper<>();
        IPage<Product>  productIPage=  productMapper
                .selectPage(new Page<>(dataPage.getPage(),dataPage.getCount()),queryWrapperProduct);
        List<Product> list = productIPage.getRecords();
        return list;
    }

    @PostMapping("/product/setProducts")
    public int setProducts(Product product)
    {
        return productMapper.insert(product);
    }

    @PostMapping("/product/setImage")
    public String setImage(MultipartFile file)
    {
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-","");

            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
            byte[] data = file.getBytes();
            //new一个文件对象用来保存图片，默认保存当前工程根目录
            File imageFile = new File(imagePath+uuid+".jpg");
            //创建输出流
            FileOutputStream outStream = new FileOutputStream(imageFile);
            //写入数据
            outStream.write(data);
            //关闭输出流
            outStream.close();
            return uuid;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

}

